﻿using Domain.Entitys.DB;
using Domain.IRepositorys.DB;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFCore.Repositorys.DB
{
    /// <summary>
    /// 仓库库位(Efcore)
    /// </summary>
    public class Db_warehouselocationRepositpry : DB_warehouse_location
    {
        private readonly MyDbContext _myContext;

        public Db_warehouselocationRepositpry(MyDbContext myContext)
        {
            _myContext = myContext;
        }


        
        /// <summary>
        /// 查询总数量
        /// </summary>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <param name="location_name"></param>
        /// <param name="location_x_position"></param>
        /// <param name="location_y_position"></param>
        /// <param name="location_z_position"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public  int Select_count_warehouse_location(string zone_code,string location_code,string location_name,int? location_x_position,int? location_y_position,int? location_z_position)
        {
            IQueryable<Warehouse_location> query = _myContext.db_warehouse_location
                .Where(e => e.Del_flag == '0' && e.zone_code==zone_code);

            

            if (!string.IsNullOrEmpty(location_code))
            {
                query = query.Where(e => e.location_code.Contains(location_code));
            }

            if (!string.IsNullOrEmpty(location_name))
            {
                query = query.Where(e => e.location_name.Contains(location_name));
            }

            if (location_x_position!=0)
            {
                query = query.Where(e => e.location_x_position ==location_x_position.Value);
            }

            if (location_y_position!=0)
            {
                query = query.Where(e => e.location_y_position == location_y_position.Value);
            }

            if (location_z_position!=0)
            {
                query = query.Where(e => e.location_z_position == location_z_position.Value);
            }

            return  query.Count();
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <param name="location_name"></param>
        /// <param name="location_x_position"></param>
        /// <param name="location_y_position"></param>
        /// <param name="location_z_position"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Warehouse_location> Select_fy_warehouse_location(string zone_code, string location_code, string location_name, int? location_x_position, int? location_y_position, int? location_z_position, int currentPage, int pageSize)
        {
            IQueryable<Warehouse_location> query = _myContext.db_warehouse_location
                .Where(e => e.Del_flag == '0' && e.zone_code == zone_code);
            if (!string.IsNullOrEmpty(location_code))
            {
                query = query.Where(e => e.location_code == location_code);
            }

            if (!string.IsNullOrEmpty(location_name))
            {
                query = query.Where(e => e.location_name.Contains(location_name));
            }

            if (location_x_position!=0)
            {
                query = query.Where(e => e.location_x_position == location_x_position.Value);
            }

            if (location_y_position != 0)
            {
                query = query.Where(e => e.location_y_position == location_y_position.Value);
            }

            if (location_z_position != 0)
            {
                query = query.Where(e => e.location_z_position == location_z_position.Value);
            }
            var pages = query.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();



            return pages;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="warehouse_location"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> warehouse_location_Add(Warehouse_location warehouse_location)
        {
           await _myContext.db_warehouse_location.AddAsync(warehouse_location);
            return await _myContext.SaveChangesAsync();
        }

        /// <summary>
        /// 仓库库位全部信息
        /// </summary>
        /// <param name="zone_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Warehouse_location> warehouse_location_Async(string zone_code)
        {
           var Warehouse_location= _myContext.db_warehouse_location.Where(e => e.Del_flag == '0' && e.zone_code == zone_code).ToList();
            return Warehouse_location;
        }
        


        /// <summary>
        /// 库位编码唯一性判断
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehouse_Location_code_judgment(string location_code,string zone_code)
        {
            return await _myContext.db_warehouse_location
           .Where(w => w.location_code == location_code && w.Del_flag == '0' && w.zone_code==zone_code)
           .CountAsync();
        }
        /// <summary>
        /// 库位名称唯一性判断
        /// </summary>
        /// <param name="warehouse_name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Warehouse_Location_name_judgment(string location_name, string zone_code)
        {
            return await _myContext.db_warehouse_location
         .Where(w => w.location_name == location_name && w.Del_flag == '0' && w.zone_code==zone_code)
         .CountAsync();
        }
        /// <summary>
        /// 库位删除
        /// </summary>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async  Task<int> warehouse_location_tombstone(string zone_code, string location_code)
        {
            var warehouse_zone=await _myContext.db_warehouse_zone.Where(e=>e.zone_code==zone_code && e.Del_flag=='0').FirstOrDefaultAsync();
            if (warehouse_zone == null) { 
            return 0;   
            }

            var inv_stock = await _myContext.inv_stock.Where(e => e.Warehouse_Code == warehouse_zone.warehouse_code && e.Del_Flag == '0' && e.Zone_Code== zone_code && 
            e.Location_Code == location_code).FirstOrDefaultAsync();
            if (inv_stock != null && inv_stock.stock_numder > 0)
            {
                // 库存存在且数量 > 0，不能删除
                return 0;
            }

            var warehouse_location=await _myContext.db_warehouse_location.Where(e=>e.location_code==location_code && e.zone_code==zone_code && e.Del_flag=='0').FirstOrDefaultAsync();

            if (warehouse_location == null)
            {
                throw new Exception("库位不存在");
            }
            warehouse_location.Del_flag = '1';


            return await _myContext.SaveChangesAsync();
        }

        /// <summary>
        /// 仓库库位冻结状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="location_freeze"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> warehouse__location_Frozenstate(int id, char location_freeze)
        {
            Warehouse_location warehouse_location = await _myContext.db_warehouse_location.FindAsync(id);

            if (warehouse_location == null) {
                return 0;
            }
            if (warehouse_location.Del_flag != '0')
            {
                return 0;
            }
            if (location_freeze == '0')
            {
                warehouse_location.location_freeze = '1';
            }
            else if (location_freeze == '1')
            {
                warehouse_location.location_freeze = '0';
            }
            return await _myContext.SaveChangesAsync();
        }
        /// <summary>
        ///修改
        /// </summary>
        /// <param name="warehouse_location"></param>
        /// <returns></returns>
        public async Task<int> warehouse__location_Update(Warehouse_location warehouse_location)
        {
           var weahouse_location_update=await _myContext.db_warehouse_location.FirstOrDefaultAsync(w=>w.location_code== warehouse_location.location_code);
            if (weahouse_location_update == null) { 
            return 0;
            }

            weahouse_location_update.location_name = warehouse_location.location_name;
            weahouse_location_update.location_max_capacity = warehouse_location.location_max_capacity;
            weahouse_location_update.location_available_capacity = warehouse_location.location_available_capacity;
            weahouse_location_update.location_used_capacity = warehouse_location.location_used_capacity;
            weahouse_location_update.location_x_position = warehouse_location.location_x_position;
            weahouse_location_update.location_y_position = warehouse_location.location_y_position;
            weahouse_location_update.location_z_position = warehouse_location.location_z_position;
            weahouse_location_update.location_allow_mix = warehouse_location.location_allow_mix;
            weahouse_location_update.location_batch_mix = warehouse_location.location_batch_mix;
            weahouse_location_update.location_enable = warehouse_location.location_enable;
            weahouse_location_update.location_freeze = warehouse_location.location_freeze;
            weahouse_location_update.remarks = warehouse_location.remarks;
            weahouse_location_update.Update_by = warehouse_location.Update_by;
            weahouse_location_update.Update_time = warehouse_location.Update_time;
            weahouse_location_update.Del_flag = warehouse_location.Del_flag;

            return await _myContext.SaveChangesAsync();

        }



        /// <summary>
        /// 判断库位的添加是否大于库区的容量
        /// </summary>
        /// <param name="warehouse_code"></param>
        /// <param name="zone_capacity"></param>
        /// <returns></returns>
        
        public async Task<int> Warehouselocation_Capacity_judgment(string zone_code, int location_max_capacity)
        {

            // 1. 找到对应库区
            var zone = await _myContext.db_warehouse_zone
                                        .Where(z => z.zone_code == zone_code && z.Del_flag == '0')
                                        .FirstOrDefaultAsync();

            if (zone == null)
                return -1; // 库区不存在或已删除

            int zoneCapacity = zone.zone_capacity; // 库区最大容量

            // 2. 统计当前库区下所有未删除库位的最大容量总和
            var existingLocations = await _myContext.db_warehouse_location
                                                     .Where(l => l.zone_code == zone_code && l.Del_flag == '0')
                                                     .ToListAsync();

            int totalUsedCapacity = existingLocations.Sum(l => l.location_max_capacity);

            // 3. 预测添加后的总容量
            int futureTotalCapacity = totalUsedCapacity + location_max_capacity;

            // 4. 判断
            return futureTotalCapacity > zoneCapacity ? 0 : 1;
        }



        /// <summary>
        /// 修改查询仓库名称
        /// </summary>
        /// <param name="location_name"></param>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <returns></returns>
     
        public async Task<int> Warehouse_Location_name_UpdateJudgment(string location_name, string zone_code, string location_code)
        {

            return await _myContext.db_warehouse_location
      .Where(w => w.location_name == location_name &&
                  w.Del_flag == '0' &&
                  w.zone_code == zone_code &&
                  w.location_code != location_code)
      .CountAsync();
        }

        public List<Warehouse_location> Warehouse_location_By_Select_Async_code(string zone_code, string location_code)
        {
            var weahouse = _myContext.db_warehouse_location.Where(e => e.Del_flag == '0'&& e.zone_code==zone_code && e.location_code == location_code).ToList();
            return weahouse;
        }


        /// <summary>
        /// 修改的容量判断
        /// </summary>
        /// <param name="zone_code"></param>
        /// <param name="location_code"></param>
        /// <param name="new_location_max_capacity"></param>
        /// <returns></returns>
       
        public async Task<int> Warehouselocation_Capacity_UpdateJudgment(string zone_code, string location_code, int new_location_max_capacity)
        {

            // 1. 找到对应库区
            var zone = await _myContext.db_warehouse_zone
                                       .Where(z => z.zone_code == zone_code && z.Del_flag == '0')
                                       .FirstOrDefaultAsync();

            if (zone == null)
                return -1; // 库区不存在或已删除

            int zoneCapacity = zone.zone_capacity; // 库区最大容量

            // 2. 统计当前库区下所有未删除库位的最大容量总和（排除当前库位）
            var existingLocations = await _myContext.db_warehouse_location
                                                    .Where(l => l.zone_code == zone_code && l.Del_flag == '0' && l.location_code != location_code)
                                                    .ToListAsync();

            int totalUsedCapacity = existingLocations.Sum(l => l.location_max_capacity);

            // 3. 预测修改后的总容量
            int futureTotalCapacity = totalUsedCapacity + new_location_max_capacity;

            // 4. 判断
            return futureTotalCapacity > zoneCapacity ? 0 : 1;
        }
    }
}
